package org.hugh.space.utils;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hugh.space.dao.Dao;
import org.hugh.space.entity.FileEntity;
import org.hugh.space.entity.UserEntity;
import org.hugh.space.entity.UserRole;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class SetupBeanImpl implements SetupBean {

	private static Log log = LogFactory.getLog(SetupBeanImpl.class);

	private Dao dao;

	public Dao getDao() {
		return dao;
	}

	public void setDao(Dao dao) {
		this.dao = dao;
	}

	@Override
	public void clear() {
		getDao().getUserDao().removeAll();
		for(FileEntity file:getDao().getFileDao().getAll()){
			getDao().getFileDao().remove(file.getId());
		}
	}

	@Override
	public void setup() {
		log.info("setup...");
		clearSessions();
		initFile();
		initUsers();
	}

	private void clearSessions() {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Query query = new Query("_ah_SESSION");
		PreparedQuery results = datastore.prepare(query);
		log.info("Deleting " + results.countEntities()
				+ " sessions from data store");
		for (Entity session : results.asIterable()) {
			datastore.delete(session.getKey());
		}
	}

	public void initFile() {

	}

	private void initUsers() {
		List<UserEntity> admins = getDao().getUserDao().getByRole(UserRole.ADMIN);
		if (admins.size() == 0) {
			UserEntity admin = new UserEntity("admin", "admin", "admin@test.com",UserRole.ADMIN);
			getDao().getUserDao().save(admin);
	        log.info("Adding admin user admin@test.com.");
		}
		List<UserEntity> guests = getDao().getUserDao().getByRole(UserRole.GUEST);
		if (guests.size() == 0) {
			UserEntity guest = new UserEntity("guest", "guest", "guest@test.com",UserRole.GUEST);
			getDao().getUserDao().save(guest);
	        log.info("Adding guest guest@test.com.");
		}
	}

}
